package com.bt7274.controller;

import com.bt7274.base.MinIOUtil;
import com.bt7274.config.MinIOConfig;
import com.bt7274.grace.result.GraceJSONResult;
import com.bt7274.grace.result.ResponseStatusEnum;
import com.bt7274.pojo.Post;
import com.bt7274.pojo.bo.PostBO;
import com.bt7274.pojo.bo.PostListBO;
import com.bt7274.pojo.vo.PostDetailVO;
import com.bt7274.pojo.vo.PostListVO;
import com.bt7274.service.PostService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/post")
public class PostController {

    @Resource
    private PostService postService;
    @Resource
    private MinIOConfig minIOConfig;
    // 查询单个帖子
    @GetMapping("/get")
    public GraceJSONResult getPost(@RequestParam String postId) {
        Post post = postService.selectPostById(postId);
        return GraceJSONResult.ok(post);
    }
    // 查询帖子详情
    @GetMapping("/detail")
    public GraceJSONResult getPostDetail(@RequestParam String postId,
                                         @RequestParam(defaultValue = "1") int page,
                                         @RequestParam(defaultValue = "10") int pageSize) {

        try {
            PostDetailVO detail = postService.getPostDetail(postId, page, pageSize);
            if (detail == null) {
                return GraceJSONResult.errorMsg("帖子不存在");
            }
            return GraceJSONResult.ok(detail);
        } catch (Exception e) {
            return GraceJSONResult.errorMsg("获取帖子详情失败"+e.getMessage());
        }

    }

    //查看某人发的帖子
    @GetMapping("/sbPost")
    public GraceJSONResult getSomeOnePosts(@RequestParam(required = false) String userId,
                                              @RequestParam(defaultValue = "1") int page,
                                            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 查询总数
            long total = postService.countSomeOnePosts(userId,page,pageSize);
            // 查询分页数据
            List<PostListVO> postList = postService.getSomeOnePosts(userId,page,pageSize);
            // 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", total);
            result.put("postList", postList);
            // 返回结果
            return GraceJSONResult.ok(result);
        } catch (Exception e) {
            return GraceJSONResult.errorMsg("获取帖子列表失败" + e.getMessage());
        }
    }



    // 查询帖子列表
    @PostMapping("/list")
    public GraceJSONResult list(@RequestBody PostListBO postListBO) {
        try {
            // 查询总数
            if(postListBO.getKeyword()==null) postListBO.setFilterPinned(true);
            long total = postService.countPostList(postListBO);
            // 查询分页数据
            List<PostListVO> postList = postService.selectPostList(postListBO);
            // 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", total);
            result.put("postList", postList);
            // 返回结果
            return GraceJSONResult.ok(result);
        } catch (Exception e) {
            return GraceJSONResult.errorMsg("获取帖子列表失败" + e.getMessage());
        }
    }

    //获取置顶帖列表
    @GetMapping("/pinnedList")
    public GraceJSONResult pinnedList(@RequestParam(required = false) String forumId) {
        try {
            List<PostListVO> postList = postService.selectPinnedPostList(forumId);
            // 返回结果
            return GraceJSONResult.ok(postList);
        } catch (Exception e) {
            return GraceJSONResult.errorMsg("获取置顶帖子列表失败" + e.getMessage());
        }
    }

    // 发布帖子
    @PostMapping("/create")
    public GraceJSONResult add(@RequestPart("postBO") PostBO postBO,
                               @RequestPart(value = "file", required = false) MultipartFile file) {
        try{
            String imageUrl = null;
            if (file != null && !file.isEmpty()) {
                String filename = file.getOriginalFilename();
                if(StringUtils.isBlank(filename)){
                    return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
                }
                filename = "image/" + dealWithFilename(filename);
                imageUrl = MinIOUtil.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream(), true);

            }
            postService.createPost(postBO,imageUrl);
            return GraceJSONResult.ok();
        }catch (Exception e) {
            return GraceJSONResult.errorMsg("发布失败"+e.getMessage());
        }
    }
    private String dealWithFilename(String filename){
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String fName =filename.substring(0,filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        return fName +"-"+uuid +suffixName;
    }

    // 更新帖子
    @PostMapping("/update")
    public GraceJSONResult update(@RequestBody PostBO postBO) {
        try{
            postService.updatePost(postBO);
            return GraceJSONResult.ok();
        }catch (Exception e) {
            return GraceJSONResult.errorMsg("更新失败");
        }
    }



    // 删除单个帖子
    @DeleteMapping("/delete/{postId}")
    public GraceJSONResult delete(@PathVariable String postId) {
        postService.deletePostById(postId);
        return GraceJSONResult.ok();
    }

    // 批量删除帖子
    @DeleteMapping("/deletePosts/{ids}")
    public GraceJSONResult deleteBatch(@PathVariable String[] ids) {
        postService.deletePostByIds(ids);
        return GraceJSONResult.ok();
    }

    //举报帖子
    @PostMapping("/report")
    public GraceJSONResult reportPost(@RequestParam String postId,
                                                @RequestParam String reason) {
        try {
            postService.reportPost(postId, reason);
            return GraceJSONResult.ok("举报成功");
        } catch (Exception e) {
            return GraceJSONResult.errorMsg("举报失败: " + e.getMessage());
        }
    }

    //管理员锁定帖子
    @PostMapping("/lock")
    public GraceJSONResult lockPost(@RequestParam String postId) {
        try {
            Post post = postService.selectPostById(postId);
            if (post == null) {
                return GraceJSONResult.errorMsg("帖子不存在");
            }
            postService.lockPost(post);
            return GraceJSONResult.ok("帖子已锁定");
        } catch (Exception e) {
            return GraceJSONResult.errorMsg("锁定帖子失败: " + e.getMessage());
        }
    }



}
